package com.foreknow.controller;

import com.foreknow.service.GuestService;
import com.foreknow.service.impl.GuestServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class ManagerServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //ServletConfig这个对象会提供一些方法来获取到web.xml中配制的初始化参数
        //String pageSize = config.getInitParameter("pageSize");
        //如果要获取到全局的初始化参数？
        String pageSize = config.getServletContext().getInitParameter("pageSize");
        System.out.println(Integer.parseInt(pageSize));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("q");
        if("list".equals(method)) {
            list(req,resp);
        }else if("delete".equals(method)) {
            delete(req,resp);
        }else if("edit".equals(method)){
            edit(req,resp);
        } else {
            update(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置从服务器端向客户端返回的内容的类型   MIME类型: text/html
        resp.setContentType("text/html;charset=UTF-8");
        //客户端向服务器端请求的编码格式（否则会产生乱码） 默认：IOS 8859-1
        req.setCharacterEncoding("UTF-8");
        //获取打印流用于向网页输出内容
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        GuestService service = new GuestServiceImpl();
        List<Object> list = service.getQueryAll();
        //通过request.setAttribute("list",list);在服务器端保存list集合
        session.setAttribute("list",list);
        //转发资源到list.jsp
        //req.getRequestDispatcher("/list.jsp").forward(req,resp);
        //如果使用重定向，页面中没有数据，因为req只有发生一次请求的时候才能获取到数据，所要可以将list保存到Session中，以达到数据共享
        resp.sendRedirect(req.getContextPath()+"/list.jsp");
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据id查询，然后跳转到update.jsp
    }

    protected void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //修改
    }
}
